#include "xtools.h"
#include <sstream>
#include <chrono>
using namespace std;

void MSleep(unsigned int ms) {
  auto beg = clock();
  for (int i = 0; i < ms; i++) {
    this_thread::sleep_for(1ms);
    if ((clock() - beg) / (CLOCKS_PER_SEC / 1000) >= ms)
      break;
  }
}
long long NowMs() { return clock() / (CLOCKS_PER_SEC / 1000); }

void XThread::Start() {
  unique_lock<mutex> lock(m_);
  static int i = 0;
  index_ = ++i;
  // 设置为未退
  is_exit_ = false;
  // 启动线程
  th_ = thread(&XThread::Main, this);
  stringstream s;
  s << "XThread::Start" << index_;
  XLOGINFO(s.str());
  // // 分离主线程与子线程 这里不做，因该由Stop控制
  // th_.detach();
}

void XThread::Stop() {
  stringstream s;
  s << "XThread::Stop() begin" << index_;
  XLOGINFO(s.str());
  is_exit_ = true;
  if (th_.joinable()) { // 判断线程是否可以等待，保真不会出错
    th_.join();
  }
  s.str("");
  s << "XThread::Stop() end" << index_;
  XLOGINFO(s.str());
}

